package org.luxor.commons.jdbc.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSchemaHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSchemaSqlParser;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import org.luxor.commons.jdbc.constant.JdbcConstants;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.context.support.WebApplicationObjectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.Yan  @date 2019/9/25$
 */
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig extends WebApplicationObjectSupport {

    /**
     * 分页插件
     */
    @Bean
    @ConditionalOnMissingBean
    public PaginationInterceptor paginationInterceptor() {
        List<ISqlParser> sqlParserList = new ArrayList<>();
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置最大单页限制数量，默认 500 条，小于 0 如 -1 不受限制
        paginationInterceptor.setLimit(JdbcConstants.LIMIT_MAX);
        // 数据隔离(分库分表)
        ApplicationContext applicationContext = getApplicationContext();
        //扫描租户行级隔离配置
        String[] handlerNames = applicationContext.getBeanNamesForType(TenantHandler.class);
        for (String handlerName : handlerNames) {
            TenantSqlParser tenantSqlParser = new TenantSqlParser();
            tenantSqlParser.setTenantHandler(applicationContext.getBean(handlerName, TenantHandler.class));
            sqlParserList.add(tenantSqlParser);
        }
        //扫描Schema隔离
        String[] handlerSchemaNames = applicationContext.getBeanNamesForType(TenantSchemaHandler.class);
        for (String handlerName : handlerSchemaNames) {
            TenantSchemaSqlParser tenantSqlParser = new TenantSchemaSqlParser();
            tenantSqlParser.setTenantSchemaHandler(applicationContext.getBean(handlerName, TenantSchemaHandler.class));
            sqlParserList.add(tenantSqlParser);
        }
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }

    /**
     * 乐观锁插件
     */
    @Bean
    @ConditionalOnMissingBean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

}